<template>

  <div>
<!--    面包屑导航-->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
<!--卡片视图-->
    <el-card>
      <el-row :gutter="20">
        <el-col :span="7">
          <el-input  v-model="queryInfo.query" clearable @clear="getUserList">
          <el-button slot="append" icon="el-icon-search" @click="getUserList"></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary"  @click="addUserDialogVisible = true" >添加用户 </el-button>
        </el-col>
      </el-row>
      <el-table
        border
        stripe
        :data="userList"
        style="width: 100%">
        <el-table-column
          type="index">
        </el-table-column>
        <el-table-column
          prop="id"
          label="id"
          width="80">
        </el-table-column>
        <el-table-column
          prop="username"
          label="姓名"
          width="80">
        </el-table-column>
        <el-table-column
          prop="sex"
          label="姓别"
          width="80">
        </el-table-column>
        <el-table-column
          prop="phone"
          label="电话">
        </el-table-column>
        <el-table-column
          prop="email"
          label="邮箱">
        </el-table-column>
        <el-table-column
          prop="birthday"
          label="生日">
        </el-table-column>
        <el-table-column
          prop="hobby"
          label="爱好">
        </el-table-column>
        <el-table-column
          prop="createTime"
          label="创建时间">
        </el-table-column>
        <el-table-column
          prop="status"
          label="状态">
<!--          作用域插槽-->
          <template slot-scope="scope">
           <el-switch
             v-model="scope.row.status"
             @change="userStateChanged(scope.row)"
             active-value="1"
             inactive-value="0"></el-switch>
          </template>
        </el-table-column>

        <!--            修改按钮-->
        <el-table-column
          label="操作">
          <template slot-scope="scope">
            <el-tooltip
              class="item"
              effect="dark"
              content="编辑"
              :enterable="false"
              placement="top">
              <el-button
                type="primary"
                icon="el-icon-edit"
                size="mini"
                circle
                @click="showEditDialog(scope.row.id)"
              ></el-button>
            </el-tooltip>
            <!--           删除 按钮 -->
            <el-tooltip class="item" effect="dark" content="删除" placement="top">
              <el-button
                type="danger"
                icon="el-icon-delete"
                size="mini"
                circle
                @click="removeUserById(scope.row.id)"
              ></el-button>
            </el-tooltip>

          </template>
        </el-table-column>
      </el-table>
<!--分页-->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pageNum"
        :page-sizes="[5, 10, 20, 30]"
        :page-size="queryInfo.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
      </el-pagination>
    </el-card>
    <!--     添加用户的对话框-->
    <el-dialog
      title="添加用户"
      :visible.sync="addUserDialogVisible"
      width="50%"
      @close="addUserDialogClosed"
    >
      <!-- 内容主体 -->
      <el-form
        :model="addUserForm"
        ref="addUserFormRef"
        :rules="addUserFormRules"
        label-width="100px"
      >
        <el-row>
          <el-col :span="12" :offset="2">
            <el-form-item
              label="用户名"
              prop="username"
            >
              <el-input v-model="addUserForm.username" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12" :offset="2">
            <el-form-item
              label="性别" >
              <el-radio-group
                v-model="addUserForm.sex">
                <el-radio  label="1">男</el-radio>
                <el-radio label="0">女</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <!--邮箱-->
        <el-row>
          <el-col :span="12" :offset="2" >
            <el-form-item
              label="邮箱"
              prop="email"
            >
              <el-input v-model="addUserForm.email" />
            </el-form-item>
          </el-col>
        </el-row>
        <!--手机-->
        <el-row>
          <el-col :span="12" :offset="2">
            <el-form-item
              label="手机"
              prop="phone"
            >
              <el-input v-model="addUserForm.phone" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12" :offset="2" >
            <el-form-item label="生日"  >
              <el-date-picker
                v-model="addUserForm.birthday"
                type="date"
                placeholder="选择日期"
                format="yyyy 年 MM 月 dd 日"
                value-format="yyyy-MM-dd">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12" :offset="2">
            <el-form-item
              label="状态" >
              <el-radio-group
                v-model="addUserForm.status">
                <el-radio  label="1">启用</el-radio>
                <el-radio label="0">停用</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <!--        爱好-->
        <el-row>
          <el-col :offset="2">
            <el-form-item label="爱好">
              <el-checkbox-group v-model="addUserForm.hobby">
                <el-checkbox label="抽烟"></el-checkbox>
                <el-checkbox label="喝酒"></el-checkbox>
                <el-checkbox label="烫头"></el-checkbox>
                <el-checkbox label="洗澡"></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <span
        slot="footer"
        class="dialog-footer"
      >
        <el-button @click="addUserDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUser">确 定</el-button>
      </span>
    </el-dialog>
<!--编辑用户按钮-->
    <el-dialog
      title="编辑用户"
      :visible.sync="editUserDialogVisible"
      width="50%"
      @close="editUserDialogClosed"
    >
      <!-- 内容主体 -->
      <el-form
        :model="editUserForm"
        ref="editUserFormRef"
        :rules="editUserFormRules"
        label-width="100px"
      >
        <el-row>
          <el-col :span="12" :offset="2">
            <el-form-item
              label="用户名"
              prop="username"
            >
              <el-input v-model="editUserForm.username" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12" :offset="2">
            <el-form-item
              label="性别" >
              <el-radio-group
                v-model="editUserForm.sex">
                <el-radio  :label=1>男</el-radio>
                <el-radio :label=0 >女</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <!--邮箱-->
        <el-row>
          <el-col :span="12" :offset="2" >
            <el-form-item
              prop="email"
              label="邮箱"
            >
              <el-input v-model="editUserForm.email" />
            </el-form-item>
          </el-col>
        </el-row>
        <!--手机-->
        <el-row>
          <el-col :span="12" :offset="2">
            <el-form-item
              prop="phone"
              label="手机"
            >
              <el-input v-model="editUserForm.phone" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12" :offset="2" >
            <el-form-item label="生日" >
              <el-date-picker
                v-model="editUserForm.birthday"
                type="date"
                placeholder="选择日期"
                format="yyyy 年 MM 月 dd 日"
                value-format="yyyy-MM-dd">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12" :offset="2">
            <el-form-item
              label="状态" >
              <el-radio-group
                v-model="editUserForm.status">
                <el-radio  :label=1>启用</el-radio>
                <el-radio :label=0>停用</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <!--        爱好-->
        <el-row>
          <el-col :offset="2">
            <el-form-item label="爱好">
              <el-checkbox-group v-model="editUserForm.hobby">
                <el-checkbox label="抽烟"></el-checkbox>
                <el-checkbox label="喝酒"></el-checkbox>
                <el-checkbox label="烫头"></el-checkbox>
                <el-checkbox label="洗澡"></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <span
        slot="footer"
        class="dialog-footer"
      >
        <el-button @click="editUserDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editUser">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { request } from '../../network/request';

export default {
  name: 'UserList',
  data() {
    // 自定义邮箱规则
    // eslint-disable-next-line consistent-return
    const checkEmail = (rule, value, callback) => {
      const regEmail = /^\w+@\w+(\.\w+)+$/;
      if (regEmail.test(value)) {
        // 合法邮箱
        return callback();
      }
      callback(new Error('请输入合法邮箱'));
    };
    // 自定义手机号规则
    // eslint-disable-next-line consistent-return
    const checkMobile = (rule, value, callback) => {
      const regMobile = /^1[34578]\d{9}$/;
      if (regMobile.test(value)) {
        return callback();
      }
      // 返回一个错误提示
      callback(new Error('请输入合法的手机号码'));
    };
    return {
      //  获取用户列表的参数对象
      queryInfo: {
        query: '',
        pageNum: 1,
        pageSize: 5,
      },
      userList: [],
      total: 0,
      addUserDialogVisible: false,
      //  添加用户
      addUserForm: {
        username: '',
        phone: '',
        email: '',
        sex: 0,
        hobby: [],
        birthday: '',
        status: 1,
      },
      // 修改用户
      editUserDialogVisible: false,
      editUserForm: {
        hobby: [],
      },
      // 编辑用户表单验证
      editUserFormRules: {
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' },
        ],
        mobile: [
          { required: true, message: '请输入手机号码', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' },
        ],
      },
      addUserFormRules: {
        phone: [
          { validator: checkMobile, trigger: 'blur' },
        ],
        email: [
          { validator: checkEmail, trigger: 'blur' },
        ],
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          {
            min: 2,
            max: 10,
            message: '用户名的长度在2～10个字',
            trigger: 'blur',
          },
        ],
      },
    };
  },
  created() {
    this.getUserList();
  },
  methods: {
    getUserList() {
      request({
        url: '/user/list',
        params: this.queryInfo,
      }).then((res) => {
        if (res.code !== 200) this.$message.error('数据获取失败');
        this.userList = res.data.list;
        this.total = res.data.total;
      });
    },
    handleSizeChange(newSize) {
      this.queryInfo.pageSize = newSize;
      this.getUserList();
    },
    handleCurrentChange(newSize) {
      this.queryInfo.pageNum = newSize;
      this.getUserList();
    },
    userStateChanged(rowInfo) {
      request({
        method: 'put',
        url: `/user/switch/${rowInfo.id}/${rowInfo.status}`,
      }).then((res) => {
        console.log(res);
        if (res.code !== 200) return this.$message.error('数据获取失败');
        return this.$message.success('状态更新成功');
      });
    },
    addUserDialogClosed() {
      this.$refs.addUserFormRef.resetFields();
    },
    addUser() {
      this.$refs.addUserFormRef.validate((validate) => {
        this.addUserForm.hobby = this.addUserForm.hobby.toLocaleString();
        if (validate) {
          request({
            method: 'post',
            params: this.addUserForm,
            url: '/user/add',
            // eslint-disable-next-line consistent-return
          }).then((res) => {
            if (res.code !== 200) return this.$message.error(res.message);
            this.$message.success(res.message);
            this.addUserDialogVisible = false;
            this.getUserList();
          });
        }
      });
    },
    // 编辑用户信息
    showEditDialog(id) {
      request({
        method: 'get',
        url: `/user/find/${id}`,
      }).then((res) => {
        if (res.code !== 200) return;
        if (res.data.hobby != null) {
          this.editUserForm = res.data;
          const hobbys = res.data.hobby.split(',');
          this.editUserForm.hobby = hobbys;
        }
      });
      this.editUserDialogVisible = true;
    },
    // 监听修改用户对话框的关闭事件
    editUserDialogClosed() {
      this.$refs.editUserFormRef.resetFields();
    },

    // 修改用户信息
    editUser() {
      // 提交请求前，表单预验证
      this.$refs.editUserFormRef.validate((valid) => {
        // console.log(valid)
        // 表单预校验失败
        if (!valid) return;
        request({
          method: 'put',
          url: '/user/edit',
          params: this.editUserForm,
        }).then((res) => {
          if (res.code !== 200) return this.$message.error('更新用户失败');
          this.editUserForm = res.data;
          this.addUserDialogVisible = true;
          return this.$message.error('更新用户成功');
        });
        this.editUserDialogVisible = true;
        this.getUserList();
      });
    },

    // 删除用户
    async removeUserById(id) {
      const confirmResult = await this.$confirm(
        '此操作将永久删除该用户, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        },
      ).catch((err) => err);
      // 点击确定 返回值为：confirm
      // 点击取消 返回值为： cancel
      if (confirmResult !== 'confirm') {
        return this.$message.info('已取消删除');
      }
      return request({
        method: 'delete',
        url: `/user/delete/${id}`,
      }).then((res) => {
        if (res.code !== 200) return this.$message.error(res.message);
        this.getUserList();
        return this.$message.success(res.message);
      });
    },
  },

};
</script>

<style  lang='less' scoped>
.el-table{
  margin-top: 20px;
  font-size: 12px;
}
</style>
